<?php

class g5_admin_menu extends Model {

    function __construct(){
        parent::__construct();
        $this->_tableName = 'g5_admin_menu';
    }

    public function getMenuList(){
        $return = $result = array();
        $result = $this->getAll('menu_id,menu_name');
        foreach($result as $row){
            $return[$row['menu_id']] = $row['menu_name'];
        }
        return $return;
    }


    function getMenus($menu_id = false){
        $select = "g5_admin_menu.menu_id,g5_admin_menu.menu_name,g5_admin_menu.menu_url,g5_admin_menu.top_id,g5_admin_menu_group.group_id,menu_order";
        $join   = array('g5_admin_menu_group'=>'menu_id=menu_id');
        $order   = "g5_admin_menu.menu_order DESC ";
        if($menu_id !== false){
            return $this->join($join)->where(array('top_id'=>$menu_id))->order($order)->getAll($select);
        }else{
            return $this->join($join)->by('menu_order', 'asc')->getAll($select);
        }
    }

    function makecache(){
        $groupmenus        = $this->getMenus(false);
        foreach ($groupmenus as $row){
            if($row['top_id'] == 0){
                $menus[$row['group_id']]['parent'][$row['menu_id']] = $row;
            }else{
                 $menus[$row['group_id']]['child'][$row['top_id']][] = $row;
            }
        }
        foreach($menus as $group=>$row){
            $cache = var_export($row, true);
            $file  = DATA_PATH.'cache/group_'.$group.'_menu.php';
            $contents = "<?php defined('SCRIPT_NAME') or die('No direct script access.');\r\n return {$cache} ?>";
            write_cache($file, $contents);
        }
    }

}